package com.jiangli.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.jiangli.entity.Dish;
import com.jiangli.entity.doubao.DoubaoRequest;
import com.jiangli.entity.doubao.DoubaoStreamResponse;
import com.jiangli.entity.doubao.Message;
import com.jiangli.service.DishService;
import com.jiangli.service.DoubaoService;
import reactor.core.publisher.Flux;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 豆包服务类，负责调用豆包API并处理流式响应
 */
@Service
public class DoubaoServiceImpl implements DoubaoService {

    @Autowired
    private WebClient webClient;
    @Autowired
    DishService dishService;



    // 豆包API地址
    @Value("${doubao.api.url}")
    private String apiUrl;

    // 豆包API密钥
    @Value("${doubao.api.key}")
    private String apiKey;
//    private static final String RECOMMEND_PREFIX = "dish:recommend:";
//    private static final String DISH_DETAIL_PREFIX = "dish:detail:";
//    private static final String DISH_METADATA_KEY = "dish:all:metadata";
//    private static final String TOTAL_COUNT_KEY = "dish:total:count";

    /**
     * 调用豆包API，流式生成响应
     * @param prompt 当前用户输入
     * @param history 历史对话消息列表
     * @return 流式文本片段
     */
    public Flux<String> generateStream(String prompt, List<Message> history) {
        // 1. 构建完整的对话列表：历史消息 + 当前输入
        List<Message> messages = new ArrayList<>();
        if (history != null) {
            messages.addAll(history);
        }
        messages.add(new Message("user", prompt));

        // 2. 构建豆包API请求参数
        DoubaoRequest request = new DoubaoRequest();
        request.setModel("doubao-pro"); // 设置模型名称
        request.setMessages(messages);  // 设置对话历史
        request.setStream(true);        // 开启流式响应

        // 3. 发送请求并处理流式响应
        return webClient.post()
                .uri(apiUrl)
                .header("Authorization", "Bearer " + apiKey) // 认证头
                .header("Content-Type", "application/json")   // 内容类型
                .bodyValue(request)                           // 请求体
                .retrieve()                                   // 执行请求
                .bodyToFlux(DoubaoStreamResponse.class)       // 解析流式响应
                .map(response -> {
                    // 提取文本片段
                    if (response.getChoices() == null || response.getChoices().isEmpty()) {
                        return "";
                    }

                    DoubaoStreamResponse.Choice choice = response.getChoices().get(0);
                    // 如果是结束标识，返回空字符串
                    if ("stop".equals(choice.getFinish_reason())) {
                        return "";
                    }

                    // 返回实际的文本内容
                    return choice.getDelta() != null ? choice.getDelta().getContent() : "";
                })
                .filter(content -> !content.isEmpty()); // 过滤空内容
    }

    @Override
    public Flux<String> generateStreamWithFood(String prompt, List<Message> history, List<Long> ids) {

        List<Dish> list = dishService.getDishesFromCacheOrDB(ids);
        StringBuilder dishNames = new StringBuilder("用户选择的菜品:");
        for (Dish dish : list) {
            dishNames.append(dish.getDishName()).append("(");
            dishNames.append("热量:").append(dish.getCalorie()).append(",");
            dishNames.append("价格:").append(dish.getPrice()).append(",");
            dishNames.append("描述信息:").append(dish.getDescription()).append("),");
        }
        String fullPrompt = "用户问题:" + prompt + " " + dishNames;
        return generateStream(fullPrompt, history);
    }


}
